import { wjlface } from "../axiosAPI/wjl";
import React, { useState, useRef, useEffect, useCallback } from "react";
import { Toast } from "react-vant";

const Face = ({ setIsFullscreenLocked }) => {
	const [image, setImage] = useState(null);
	const [istrue, setIstrue] = useState(null);
	const [isVideoVisible, setIsVideoVisible] = useState(true);
	const [isVerified, setIsVerified] = useState(false);
	const videoRef = useRef(null);
	const canvasRef = useRef(null);
	const personId = sessionStorage.getItem("sid");

	const mediaStreamRef = useRef(null);
	const timeoutRef = useRef(null);
	const randomTimeoutRef = useRef(null);

	const startCamera = useCallback(() => {
		if (videoRef.current) {
			navigator.mediaDevices
				.getUserMedia({ video: true })
				.then((stream) => {
					mediaStreamRef.current = stream;
					videoRef.current.srcObject = stream;
				})
				.catch((err) => {
					console.error("Error accessing camera:", err);
					Toast.fail("无法访问摄像头");
				});
		}
	}, []);

	const stopCamera = useCallback(() => {
		if (mediaStreamRef.current) {
			mediaStreamRef.current.getTracks().forEach((track) => track.stop());
			mediaStreamRef.current = null;
			if (videoRef.current) {
				videoRef.current.srcObject = null; // 释放视频流
			}
		}
	}, []);

	const verifyFace = useCallback(
		async (base64Image) => {
			try {
				const response = await wjlface({
					image: base64Image.split(",")[1],
					personId: personId,
				});
				console.log("Verification result:", response.data);
				const matchResult = response.data.IsMatch;

				if (matchResult !== istrue) {
					setIstrue(matchResult);
					setIsVerified(true);
				}

				if (matchResult) {
					stopCamera();
					setIsVideoVisible(false);
					return;
				}

				console.log("Verification failed, retrying...");
				setTimeout(() => {
					if (videoRef.current) {
						captureImage();
					}
				}, 5000);
			} catch (error) {
				Toast.fail("暂无此人员");
				console.error("Error verifying face:", error);

				setTimeout(() => {
					if (videoRef.current) {
						captureImage();
					}
				}, 5000);
			}
		},
		[istrue, personId, stopCamera],
	);

	const captureImage = useCallback(() => {
		if (!videoRef.current) {
			console.error("Video reference is not available.");
			return;
		}

		const canvas = canvasRef.current;
		const video = videoRef.current;
		canvas.width = video.videoWidth;
		canvas.height = video.videoHeight;
		const context = canvas.getContext("2d");
		context.drawImage(video, 0, 0);
		const base64Image = canvas.toDataURL("image/jpeg");
		setImage(base64Image);
		verifyFace(base64Image);
	}, [verifyFace]);

	useEffect(() => {
		startCamera();
		timeoutRef.current = setTimeout(() => {
			if (videoRef.current) {
				captureImage();
			}
		}, 3000);

		return () => {
			stopCamera();
			clearTimeout(timeoutRef.current);
			clearTimeout(randomTimeoutRef.current);
		};
	}, [startCamera, stopCamera, captureImage]);

	useEffect(() => {
		if (isVerified) {
			Toast[istrue ? "success" : "fail"](istrue ? "验证成功" : "验证失败");
			if (istrue) {
				setIsFullscreenLocked(false);
				const randomTime = Math.floor(Math.random() * 5400000) + 60000;
				randomTimeoutRef.current = setTimeout(() => {
					setIsVideoVisible(true);
					captureImage();
				}, randomTime);
			}
		}
	}, [istrue, isVerified, setIsFullscreenLocked, captureImage]);

	return (
		<div className="flex flex-col items-center">
			{isVideoVisible && <video style={{ width: "100px", marginLeft: "50px" }} ref={videoRef} autoPlay className="border border-gray-400"></video>}
			<canvas ref={canvasRef} style={{ display: "none" }} />
		</div>
	);
};

export default Face;
